//
//  SumViewController.swift
//  DSP
//
//  Created by tucici on 2024/5/14.
//

import UIKit
import SwiftyJSON
import RealmSwift
import TCCKit

private enum CellType{
    case output(_ array:[OutputModel])
    case input(_ types:[InputCellBtn], _ array:[ChannelModel])
    case delay(_ array:[ChannelModel])
}
private let names = ["CH1","CH2","CH3","CH4","CH5","CH6","CH7","CH8"]
class SumViewController: DSBaseController {
    private lazy var array = [CellType]()
    private lazy var input_array : [ChannelModel] = {
        //        let array = RealmHelper.queryObject(objectClass: InputModel())
        //        let temp = array.map{$0.copy() as! InputModel}
        let array2 = names.map{JSON(["name":$0,"enable":true])}
        let temp2 = array2.map{InputModel.json($0)}
        return temp2
    }()
    private lazy var copy_array : [ChannelModel] = {
        return APP.CHM.out_array.map{
            let copy = $0.copy() as! ChannelModel
            copy.select = false
            return copy
        }
    }()
    private lazy var input_btnTypes : [InputCellBtn] = {
        return [InputCellBtn(text: "Assign", select: false),InputCellBtn(text: "Custom", select: false)]
    }()
    private lazy var copy_btnTypes : [InputCellBtn] = {
        return [InputCellBtn(text: "Copy", select: false),InputCellBtn(text: "Erase", select: false)]
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        select_ch_index = 100
    }
    
    override func initUI() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(OutputCell.self, forCellReuseIdentifier: OutputCell.ID())
        tableView.register(InputCell.self, forCellReuseIdentifier: InputCell.ID())
        tableView.register(DelayCell.self, forCellReuseIdentifier: DelayCell.ID())
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(KUITabBarHeight)
        }
    }
    
    override func initData() {
        super.initData()
        BLE.scanWithOther = { peripheral in
            return peripheral.name?.contains(DeviceName) ?? false
        }
        
        BLE.startScan(result: nil)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 6, execute: {
            BLE.stopScan()
        })
        
        BLE.connectBlock = { status in
            print("====statas = \(status)")
            if status == .connectedSucces && self.currentVC().className != SearchController.className{
                BLE.delegate = DSBleDataTool.share
                DSShowView.show()
            }
        }
    }
    
    @objc override func updateData() {
        super.updateData()
        array = [.output(APP.CHM.out_array),
                 .input(input_btnTypes, input_array),
                 .input(copy_btnTypes,copy_array),
                 .delay(APP.CHM.array)]
        tableView.reloadData()
        
        let array = input_array.map{$0.copy() as! ChannelModel}
        //RealmHelper.updateObjects(objects: array)
    }
    
    @objc override func resetAction(){
        let array2 = names.map{JSON(["name":$0,"enable":true])}
        input_array = array2.map{InputModel.json($0)}
        copy_array = APP.CHM.out_array.map{
            let copy = $0.copy() as! ChannelModel
            copy.select = false
            return copy
        }
        
        input_btnTypes = [InputCellBtn(text: "Assign", select: false),InputCellBtn(text: "Custom", select: false)]
        copy_btnTypes = [InputCellBtn(text: "Copy", select: false),InputCellBtn(text: "Erase", select: false)]
        updateData()
    }
    
    override func sendData(){
        ///output
        for output in APP.CHM.out_array{
            _ = BLEData.sum(output).write
            _ = BLEData.delay(output).write
        }
    }
    
    ///特别发送copy的通道的 均衡器， 增益， 分频
    func sendCopyData(_ copy:ChannelModel){
        ///1，copy的均衡器
        for j in 0..<copy.signArray.count{
            let sign = copy.signArray[j]
            _ = BLEData.EQ([copy], j, sign).write
        }
        ///2，copy的增益
        _ = BLEData.mute(copy).write
        _ = BLEData.phase(copy).write
        ///3, copy的分频
        _ = BLEData.crossOver(copy, copy.highPass.select).write
        _ = BLEData.crossOver(copy, (copy.lowPass.select)).write
    }
}

//MARK: - InputCellDelegate
extension SumViewController : InputCellDelegate{
    func press(text: String, longpress: Bool) {
        switch text{
        case "Assign":
            APP.CHM.inputSelectType = 1
            input_btnTypes[0].select = true
            input_btnTypes[1].select = false
            
            _ = APP.CHM.out_array.enumerated().map{
                $0.element.select = true
                $0.element.enable = true
                ///清空custom
                $0.element.initInputArr()
            }
            _ = input_array.map{
                $0.enable = false
                $0.select = false
            }
            _ = copy_array.map{
                // $0.enable = false
                $0.select = false
            }
        case "Custom":
            APP.CHM.inputSelectType = 2
            input_btnTypes[0].select = false
            input_btnTypes[1].select = true
            
            var select_output : OutputModel? = nil
            _ = APP.CHM.out_array.map{ elemnt in
                elemnt.select = select_output == nil && Array(elemnt.inputArr.filter{$0 != ""}).count > 0
                elemnt.enable = true
                ///记住第一个选中的output
                if elemnt.select && select_output == nil{
                    select_output = elemnt
                }
            }
            _ = input_array.map{
                $0.enable = true
                $0.select = select_output != nil && select_output!.inputArr_custom.contains("\($0.num)")
            }
            _ = copy_array.map{
                // $0.enable = true
                $0.select = false
            }
            if select_output == nil || select_output?.inputArr_custom.count ?? 0 == 0{
                updateData()
                return
            }
        case "Copy":
            copy_btnTypes[0].select = true
            copy_btnTypes[1].select = false
        case "Erase":
            copy_btnTypes[0].select = false
            copy_btnTypes[1].select = true
            _ = copy_array.map{
                // $0.enable = true
                $0.select = false
            }
        default:
            break
        }
        updateData()
        sendData()
    }
    
    func select(index: IndexPath, type:InputCellBtn) {
        /// Assign  |  Custom
        if (type.select && type.text == "Assign") || (type.select && type.text == "Custom"){
            guard let inputCH = input_array[index.row] as? ChannelModel else{return}
            guard let outputCH = APP.CHM.out_array.filter({$0.select}).first else {return}
            inputCH.select = !inputCH.select
            if outputCH.inputArr_custom.contains(where: {$0 == "\(inputCH.num)"}) || inputCH.select == false{
                outputCH.inputArr_custom[inputCH.num - 1] = ""
            }else{
                outputCH.inputArr_custom[inputCH.num - 1] = "\(inputCH.num)"
            }
            if APP.CHM.inputSelectType == 2{
                let select_model = copy_array.first(where: {$0.select}) ?? OutputModel()
                copy_array = APP.CHM.out_array.map{
                    let copy = $0.copy() as! ChannelModel
                    copy.select = copy.num == select_model.num
                    return copy
                }
            }
        }
        /// Copy
        else if type.select && type.text == "Copy"{
            guard let outputCH = copy_array[index.row] as? OutputModel else{return}
            _ = copy_array.enumerated().map{$0.element.select = index.row == $0.offset}
            
            
            ///copy弹窗的逻辑
            let vc = CopyController()
            present(vc, animated: false)
            vc.array = copy_array.enumerated().map{
                let copy = $0.element.copy() as! OutputModel
                copy.enable = $0.offset != index.row
                return copy
            }
            
            
            ///copy后的逻辑处理
            vc.block = {[weak self] model in
                ///1，先copy，output通道的合频混音
                guard let to_copy_output = APP.CHM.out_array.first(where: {$0.num == model.num }) else {return}
                let copyArr = List<String>()
                for str in outputCH.inputArr_custom {
                    copyArr.append(str.copy() as! String)
                }
                to_copy_output.inputArr_custom = copyArr
                
                
                ///2，再copy，对应的通道的分频，增益，均衡
                guard let to_copy_ch = APP.CHM.array.first(where:{$0.num == model.num}) else{return}
                guard let from_copy_ch = APP.CHM.array.first(where:{$0.num == outputCH.num}) else{return}
                
                ///这里做copy复制操作
                to_copy_ch.delay = from_copy_ch.delay
                to_copy_ch.mute = from_copy_ch.mute
                to_copy_ch.phase = from_copy_ch.phase
                to_copy_ch.maxVolume = from_copy_ch.maxVolume
                to_copy_ch.minVolume = from_copy_ch.minVolume
                to_copy_ch.Volume = from_copy_ch.Volume
                to_copy_ch.highPass = from_copy_ch.highPass.copy() as? FilterModule
                to_copy_ch.lowPass = from_copy_ch.lowPass.copy() as? FilterModule
                let copiedSignArray = List<SignModule>()
                for sign in from_copy_ch.signArray {
                    copiedSignArray.append(sign.copy() as! SignModule)
                }
                to_copy_ch.signArray = copiedSignArray
                self?.sendCopyData(to_copy_ch)
                self?.updateData()
                self?.sendData()
            }
        }
        updateData()
        sendData()
    }
    
    func changeName(input: ChannelModel, index: IndexPath) {
        for ch in input_array{
            if ch.num != input.num{continue}
            ch.name = input.name
        }
        updateData()
    }
}

//MARK: - OutputCellDelegate
extension SumViewController : OutputCellDelegate{
    func changeName(output: OutputModel, index: IndexPath) {
        for ch in APP.CHM.array{
            if ch.num != output.num{continue}
            ch.name = output.name
            // RealmHelper.updateObject(object: ch.copy())
        }
        for ch in copy_array{
            if ch.num != output.num{continue}
            ch.name = output.name
            // RealmHelper.updateObject(object: ch.copy())
        }
        NotifyTool.post(updateChannelManager)
    }
    
    func select(output: OutputModel, index: IndexPath) {
        _ = APP.CHM.out_array.map{ $0.select = $0.num == output.num }
        _ = input_array.map{ elemnt in
            elemnt.select = output.inputArr.contains("\(elemnt.num)")
        }
        updateData()
        sendData()
    }
}

//MARK: - DelayCellDelegate
extension SumViewController : DelayCellDelegate{
    func select(ch: ChannelModel, index: IndexPath) {
        _ = APP.CHM.array.map{$0.select = ch.num == $0.num}
        updateData()
        sendData()
        select_ch_index = index.row
    }
}

//MARK: - UITableViewDataSource
extension SumViewController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch array[indexPath.row]{
        case let .output(array):
            let cell = tableView.dequeueReusableCell(withIdentifier: OutputCell.ID()) as! OutputCell
            cell.array = array
            cell.delegate = self
            return cell
        case let .input(types,array):
            let cell = tableView.dequeueReusableCell(withIdentifier: InputCell.ID()) as! InputCell
            cell.types = types
            cell.array = array
            cell.delegate = self
            return cell
        case let .delay(array):
            let cell = tableView.dequeueReusableCell(withIdentifier: DelayCell.ID()) as! DelayCell
            cell.array = array
            cell.delegate = self
            return cell
        }
    }
}

//MARK: - UITableViewDelegate
extension SumViewController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return chartView.bounds.height
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        view.addSubview(chartView)
        chartView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
